package com.freestyle.common.spring.support;

import com.freestyle.common.protocols.JSONData;
import org.apache.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
* @author rocklee 
* @version 
* Create date：2019年5月10日 下午5:56:47
*/
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
	private Logger log= Logger.getLogger(getClass());
	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
		/*
		//获取当前处理请求的controller的方法
        String methodName=methodParameter.getMethod().getName(); 
        // 不拦截/不需要处理返回值 的方法
        String method= "loginCheck"; //如登录
        //不拦截
        return !method.equals(methodName);
        */
		/*String lvsMethodName=methodParameter.getMethod().getName();
		return lvsMethodName.startsWith("list")||lvsMethodName.startsWith("update")||lvsMethodName.startsWith("get")||
				lvsMethodName.startsWith("copy");*/
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType,
                                Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                ServerHttpResponse response) {
		ResponseBody lvResBodyFlag=methodParameter.getMethod().getAnnotation(ResponseBody.class);
		if (!response.getHeaders().containsKey("Content-Type")) {
			if (body != null && body instanceof ModelAndView) {
				response.getHeaders().add("Content-Type","text/html; charset=UTF-8");
			} else {
				response.getHeaders().add("Content-Type","application/json; charset=UTF-8");
			}
		}
		if (lvResBodyFlag==null) return body;
		Class<?> lvRetClassz= methodParameter.getMethod().getReturnType();
		if (body instanceof Exception){
			response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
			return new JSONData((Exception)body);
		}
		if (lvRetClassz!=void.class) return body;
		//只是为 Controller里面的方法返回类型为void的,派一个正常的JSONData数据包发回去.
		return new JSONData();
		/*log.debug(body);
		log.debug(methodParameter);
		String lvsMethodName=methodParameter.getMethod().getName();
		Class<?> lvRetClassz= methodParameter.getMethod().getReturnType();
		//log.debug(lvRetClassz);
		return body!=null?body: new JSONData();*/
	}
}
